package com.minsus.secretmailbox;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.util.Log;

import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;

public class OpenContact extends Plugin
{
    private static final int PICK_CONTACT = 1;
    private String callback;

    @Override
    public PluginResult execute(String action, JSONArray args, String callbackId)
    {
    	Log.d("test", "test execute action=" + action);
        startContactActivity();
        PluginResult mPlugin = new PluginResult(PluginResult.Status.NO_RESULT);
        mPlugin.setKeepCallback(true);
        this.callback = callbackId;
        return mPlugin;
    }

    public void startContactActivity()
    {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
        this.ctx.startActivityForResult((Plugin) this, intent, PICK_CONTACT);
    }

    @Override
    public void onActivityResult(int reqCode, int resultCode, Intent data)
    {
        String name = null;
        String number = null;
        int result = 0;
        
        switch (reqCode)
        {
            case (PICK_CONTACT):
                if (resultCode == Activity.RESULT_OK)
                {
                    Uri contactData = data.getData();
                    Cursor c = this.ctx.managedQuery(contactData, null, null, null, null);
                    
                    if (c.moveToFirst())
                    {
                        //contact ID
                        String cID = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
                        String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                        
                        if (Integer.parseInt(hasPhone) == 1)
                        {
                            Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
                            String selection = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "='" + cID + "'";
                            Cursor pc = this.ctx.managedQuery(uri, null, selection, null, null);
                            
                            while (pc.moveToNext())
                            {
                            	String temp = pc.getString(pc.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            	
                            	if(CheckValue.getInstance().checkTypeMobileNumber(temp)) {	// 핸드폰 번호 체크
                            		number = temp;
                                	break; // 핸드폰 번호라면 중지
                            	}
                            }
                        }
                        name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
                        result = 1;
                    }
                }

                JSONObject jo = new JSONObject();
                try
                {
                    jo.put("name", name);
                    jo.put("phone", number);
                    jo.put("result", result);
                }
                catch (JSONException e)
                {
                    e.printStackTrace();
                }
                this.success(new PluginResult(PluginResult.Status.OK, jo), this.callback);
            break;
        }
    }
    
    /**
     	   *  해당 Cursor 의 DB를 로그로 표시하는 테스트용 함수
     * @param cursor
     */
    public void logDBTable(Cursor cursor) {
        int i = 0;
        String logCursorName = "";
        while (i < cursor.getColumnCount()) {
            logCursorName += cursor.getColumnName(i) + "\t";
            i++;
        }
        Log.d("test",
                "=====================================================================");
        Log.d("test", "title:: " + logCursorName);
        while (cursor.moveToNext()) {
            int total = cursor.getColumnCount();
            String logString = "";
            for (i = 0; i < total; i++) {
                logString += cursor.getString(i) + "\t";
            }
            Log.d("test", "data :: " + logString);
        }
        Log.d("test",
                "=====================================================================");
    }
}
